#include "../source/server.hpp"

// void HandleClose(Channel* channel) {
//     // std::cout << "close: " << channel->Fd() << std::endl;
//     DBG_LOG("close fd : %d", channel->Fd());
//     channel->Remove(); // 移除监控
//     delete channel;
// }
// void HandleRead(Channel* channel) {
//     int fd = channel->Fd();
//     char buff[1024] = {0};
//     int ret = recv(fd, buff, 1023, 0);
//     if (ret <= 0) {
//         // channel->Remove();
//         return HandleClose(channel);
//     }
//     DBG_LOG("%s", buff);
//     channel->EnableWrite(); // 启动可写事件
//     // std::cout << buff << std::endl;
// }
// void HandleWrite(Channel* channel) {
//     int fd = channel->Fd();
//     const char* data = "1111111111111111";
//     int ret = send(fd, data, strlen(data), 0);
//     if (ret < 0) {
//         return HandleClose(channel);
//     }
//     channel->DisableWrite(); // 关闭写监控
// }
// void HandleError(Channel* channel) {
//     return HandleClose(channel);
// }
// void HandleEvent(EventLoop* loop, Channel* channel, uint64_t timerid) {
//     loop->TimerRefresh(timerid);
// }


std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;
EventLoop base_loop;
std::vector<LoopThread> threads(2);
int next_loop = 0;
LoopThreadPool* loop_pool;
void ConnectionnDestroy(const PtrConnection& conn) {
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection& conn) {
    DBG_LOG("NEW CONNECTION: %p", conn.get());
}
void OnMessage(const PtrConnection& conn, Buffer* buf) {
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadableSize());
    std::string str = "hello world";
    conn->Send(str.c_str(), str.size());
    conn->Shutdown();
}

void NewConnection(int fd) {

    conn_id++;

    PtrConnection conn(new Connection(loop_pool->NextLoop(), conn_id, fd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2)); 
    conn->SetClosedCallback(std::bind(ConnectionnDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(10);// 启动非活跃销毁
    conn->Established();// 就绪初始化
    _conns.insert(std::make_pair(conn_id, conn));
    DBG_LOG("NEW -----------");
}


int main() 
{
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    Acceptor acceptor(&base_loop, 8888);

    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1)); // 回调中，获取新链接创建Channel并且添加监控
    acceptor.Listen();
    base_loop.Start();

    return 0;
}